package com.code.aspectj.aspectj;

import android.text.TextUtils;

import com.code.aspectj.annotation.Statistics;
import com.code.aspectj.util.P;
import com.code.aspectj.util.ReflectUtils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.code.aspectj.AppInterceptor.TAG;

/**
 * Created by RLZ
 * on 2021/12/23
 */
@Aspect
public class StatisticsAspect {

    /**
     * 带有 Statistics 注解的所有连接点
     */
    @Pointcut("within(@com.code.aspectj.annotation.Statistics *)")
    public void withinAnnotatedClass() {
    }

    /**
     * 带有 Statistics 注解的所有类，除去 synthetic 修饰的方法
     */
    @Pointcut("execution(!synthetic * *(..)) && withinAnnotatedClass()")
    public void methodInsideAnnotatedType() {
    }
    /**
     * 带有 Statistics 注解的方法
     */
    @Pointcut("execution(@com.code.aspectj.annotation.Statistics * *(..)) || methodInsideAnnotatedType()")
    public void method() {
    }

    @Around("method() && @annotation(statistics)")
    public void aroundJoinPoint(ProceedingJoinPoint joinPoint, Statistics statistics) throws Throwable {
        //获取url
        if (TextUtils.isEmpty(statistics.value())) return;

        P.d(TAG,"执行广告统计, 开始执行 Url = " + statistics.value());

        Object result = joinPoint.proceed();

        if (result == null) {
            executeStatistics(new HashMap<>(), statistics.value());
            return;
        }

        HashMap<String, String> p = result instanceof Map ? (HashMap<String, String>) result : new HashMap<>();

        for (String key : p.keySet()) {
            P.d(TAG,"执行广告统计, 参数 = " + key);
        }

        executeStatistics(p, statistics.value());

    }

    private void executeStatistics(HashMap<String, String> map, String url) {
        ReflectUtils.invoke(map, url);
    }
}
